<template>
  <div class="value-domain">
    <el-form :model="formData" label-width="100px">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="值域" label-width="50px">
            <el-input v-model="queryParams.value" clearable placeholder="请输入值域名称" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-button style="margin-left: 20px" type="primary" @click="handleQuery">查询</el-button>
        </el-col>
      </el-row>

      <div class="button-group-top">
        <el-button type="primary" @click="handleExportField">导出</el-button>
        <ImportExcel action="/Basic/Enum/Import" @success="handleImportSuccess" />
        <el-button type="primary" @click="handleAddField">新增</el-button>
      </div>

      <el-table :data="tableData" border style="width: 100%; margin-top: 20px" v-loading="loading">
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="value" label="值" align="center"> </el-table-column>
        <el-table-column prop="group" label="值名称" align="center"> </el-table-column>
        <el-table-column prop="desc" label="字段类型" align="center"> </el-table-column>
        <el-table-column label="操作" width="200" align="center">
          <template #default="scope">
            <el-button type="primary" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="danger" @click="handleDelete(scope.row.enumID)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="queryParams.pageNo"
          v-model:page-size="queryParams.pageSize"
          :total="queryParams.total"
          :page-sizes="[10, 20, 30, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>

      <div class="button-group">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </div>
    </el-form>

    <el-dialog
      v-model="dialogVisible"
      :title="dialogForm.enumID ? '编辑值域' : '新增值域'"
      width="500px"
      :close-on-click-modal="false"
      destroy-on-close
      center
      align-center
    >
      <el-form ref="dialogFormRef" :model="dialogForm" :rules="dialogRules" label-width="80px">
        <el-form-item label="值" prop="value">
          <el-input v-model="dialogForm.value" placeholder="请输入值" />
        </el-form-item>
        <el-form-item label="值域名称" prop="group">
          <el-input v-model="dialogForm.group" placeholder="请输入值域名称" />
        </el-form-item>
        <el-form-item label="字段类型" prop="desc">
          <el-select v-model="dialogForm.desc" placeholder="请选择" style="width: 240px">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleDialogCancel">取消</el-button>
          <el-button type="primary" @click="handleDialogSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import http from '@/util/http1'
import { ref, reactive, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import ImportExcel from '../../../components/common/UploadFile.vue'

const emit = defineEmits(['cancel', 'submit'])

const props = defineProps({
  editData: {
    type: Object,
    default: () => ({}),
  },
})

const queryParams = reactive({
  value: '',
  pageNo: 1,
  pageSize: 10,
  total: 0,
})

const tableData = ref([
  {
    groupName: '111',
    value: '222',
  },
])
const loading = ref(false)
const handleImportSuccess = () => {
  getList()
}

const getList = async () => {
  loading.value = true
  try {
    const res = await http.post('/Basic/Enum/PageList', queryParams)
    tableData.value = res.data.list
    queryParams.total = res.data.total
  } catch (error) {
    ElMessage.error('获取数据失败')
  } finally {
    loading.value = false
  }
}

const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

const handleSizeChange = (val) => {
  queryParams.pageSize = val
  getList()
}

const handleCurrentChange = (val) => {
  queryParams.pageNo = val
  getList()
}

onMounted(() => {
  getList()
})

const formData = reactive({
  value: '',
  tableData: [{ value: '111', groupName: '222' }],
})

const handleDelete = (enumID) => {
  ElMessageBox.confirm('确认要删除这条数据吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      var enumIDs = []
      enumIDs[0] = enumID
      http.get('/Basic/Enum/Del?enumIDs=' + enumIDs, {}).then((res) => {
        if (res.flag) {
          getList()
          ElMessage.success('删除成功')
        } else {
          ElMessage.error(res.msg)
        }
      })
    })
    .catch(() => {
      ElMessage.info('已取消删除')
    })
}

const dialogVisible = ref(false)
const dialogFormRef = ref(null)
const dialogForm = reactive({
  value: '',
  desc: '',
  enumID: '',
  group: '',
  text: '测试222',
  value: '',
})

const options = [
  { value: '1', label: '数值' },
  { value: '2', label: '诊断编码' },
  { value: '3', label: '手术编码' },
]

const dialogRules = {
  value: [{ required: true, message: '请输入值', trigger: 'blur' }],
  group: [{ required: true, message: '请输入值域名称', trigger: 'blur' }],
  desc: [{ required: true, message: '请输入字段类型', trigger: 'blur' }],
}

const handleAddField = () => {
  resetForm()
  dialogForm.value = ''
  dialogForm.group = ''
  dialogForm.enumID = ''
  dialogForm.desc = ''
  dialogVisible.value = true
}

const handleEdit = (row) => {
  dialogForm.value = row.value
  dialogForm.group = row.group
  dialogForm.enumID = row.enumID
  dialogForm.desc = row.desc
  dialogVisible.value = true
}

const handleDialogSubmit = async () => {
  if (!dialogFormRef.value) return

  try {
    await dialogFormRef.value.validate()

    const res = await http.post('/Basic/Enum/AddOrUpdate', dialogForm)
    if (res.flag) {
      ElMessage.success(dialogForm.enumID ? '修改成功' : '新增成功')
      dialogVisible.value = false
      getList()
    } else {
      ElMessage.error(res.msg)
    }
  } catch (error) {
    console.error('表单验证失败:', error)
  }
}

const handleDialogCancel = () => {
  resetForm()
  dialogForm.enumID = ''
  dialogVisible.value = false
}

const resetForm = () => {
  if (dialogFormRef.value) {
    dialogFormRef.value.resetFields()
    dialogForm.enumID = ''
  }
}

const handleCancel = () => {
  emit('cancel')
}

const handleSubmit = () => {
  emit('submit', { ...formData })
}

watch(
  () => props.editData,
  (newVal) => {
    if (newVal && Object.keys(newVal).length) {
      queryParams.value = newVal.name
      handleQuery()
    }
  },
  { immediate: true },
)
</script>

<style lang="less" scoped>
.value-domain {
  padding: 20px;

  .button-group {
    margin-top: 20px;
    text-align: center;
  }

  .button-group-top {
    display: flex;
    align-items: center;
    gap: 10px;
    margin-bottom: 20px;

    :deep(.el-button) {
      height: 32px;
      line-height: 32px;
      padding: 0 15px;
    }

    :deep(.import-upload) {
      .el-button {
        height: 32px;
        line-height: 32px;
        padding: 0 15px;
      }
    }
  }

  :deep(.el-form-item) {
    margin-bottom: 18px;
  }

  :deep(.el-table) {
    .el-input {
      width: 100%;
    }
  }
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>
